package com.jxdinfo.hussar.cloud.module.example.dljc.basketpoint.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jxdinfo.hussar.cloud.module.example.dljc.basketdata.dao.BasketDataMapper;
import com.jxdinfo.hussar.cloud.module.example.dljc.basketdata.model.BasketData;
import com.jxdinfo.hussar.cloud.module.example.dljc.basketpoint.dao.BasketPointMapper;
import com.jxdinfo.hussar.cloud.module.example.dljc.basketpoint.model.BasketPoint;
import com.jxdinfo.hussar.cloud.module.example.dljc.basketpoint.service.BasketPointService;
import com.jxdinfo.hussar.cloud.module.example.dljc.basketpoint.vo.BasketImgPointVO;
import com.jxdinfo.hussar.cloud.module.example.dljc.basketpoint.vo.BasketPointPageVO;
import com.jxdinfo.hussar.cloud.module.example.dljc.basketpoint.vo.BasketPointSearchVO;
import com.jxdinfo.hussar.cloud.module.example.dljc.basketpoint.vo.BasketPointVO;
import com.jxdinfo.hussar.cloud.module.example.tjjc.towercrane.vo.DeviceInfoVO;
import com.jxdinfo.hussar.cloud.module.example.tjjc.util.DateUtil;
import com.jxdinfo.hussar.platform.core.base.apiresult.ApiResponse;
import com.jxdinfo.hussar.platform.core.utils.BeanUtil;
import com.jxdinfo.hussar.support.datasource.annotations.HussarDs;
import com.jxdinfo.hussar.support.mp.base.service.impl.HussarServiceImpl;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 吊篮监测点服务实现类
 */
@Service("dljc.basketpoint.BasketPointServiceImpl")
@HussarDs("master")
public class BasketPointServiceImpl extends HussarServiceImpl<BasketPointMapper, BasketPoint> implements BasketPointService {

    private static final Logger logger = LoggerFactory.getLogger(BasketPointServiceImpl.class);

    private static final String RETURN_CODE = "0";

    @Autowired
    private BasketPointMapper basketPointMapper;
    @Autowired
    private BasketDataMapper basketDataMapper;

    @Override
    public ApiResponse<String> add(BasketPointSearchVO basketPointSearchVO) {
        QueryWrapper<BasketPoint> wrapper = new QueryWrapper<>();
        wrapper.eq("point_name", basketPointSearchVO.getPointName());
        wrapper.eq("ty_delete_status", 0);
        BasketPoint point = basketPointMapper.selectOne(wrapper);
        if (ObjectUtils.isNotEmpty(point)) {
            return ApiResponse.fail("添加失败，监测点名称重复！");
        }

        QueryWrapper<BasketPoint> wrapperPoint = new QueryWrapper<>();
        wrapperPoint.eq("device_code", basketPointSearchVO.getDeviceCode());
        wrapperPoint.eq("ty_delete_status", 0);
        BasketPoint detectionPoint = basketPointMapper.selectOne(wrapperPoint);
        if (ObjectUtils.isNotEmpty(detectionPoint)) {
            return ApiResponse.fail("添加失败，设备已被添加！");
        }

        BasketPoint basketPoint = new BasketPoint();
        BeanUtil.copyProperties(basketPointSearchVO, basketPoint);
        basketPoint.setTyCreateTime(DateUtil.toLocalDateTime(new Date()));
        basketPoint.setTyCreateUserid("ContextUtil.getUserId()"); //todo
        basketPoint.setTyCreateUserName("ContextUtil.getUserName()"); //todo


        basketPointMapper.insert(basketPoint);

        // 添加实时数据
        for (int i = 1; i <= 3; i++) {
            BasketData basketData = new BasketData();
            basketData.setUnloaId(basketPoint.getId());
            basketData.setUnloadName(basketPoint.getPointName());
            basketData.setDataStatus(Integer.valueOf(basketPoint.getDataStatus()));
            basketData.setDataType(i);
            if (i == 1) {
                basketData.setWarnValue(basketPoint.getWarnAngleValue());
                basketData.setErrorValue(basketPoint.getErrorAngleValue());
            } else if (i == 2) {
                basketData.setWarnValue(basketPoint.getWarnLoadValue());
                basketData.setErrorValue(basketPoint.getErrorLoadValue());
            } else if (i == 3) {
                basketData.setWarnValue(basketPoint.getWarnCurrentValue());
                basketData.setErrorValue(basketPoint.getErrorCurrentValue());
            }

            basketData.setTyProjectCode(basketPoint.getTyProjectCode());
            basketData.setTyCreateTime(DateUtil.toLocalDateTime(new Date()));
            basketData.setTyCreateUserid("ContextUtil.getUserId()"); //todo
            basketData.setTyCreateUserName("ContextUtil.getUserName()"); //todo
            basketDataMapper.insert(basketData);
        }

        return ApiResponse.success();
    }

    @Override
    public ApiResponse<BasketPointPageVO> findByPage(BasketPointSearchVO basketPointSearchVO) {
        QueryWrapper<BasketPoint> wrapper = new QueryWrapper<>();

        if(ObjectUtils.isNotEmpty(basketPointSearchVO.getPointName())) {
            wrapper.like("point_name", basketPointSearchVO.getPointName());
        }
        if(ObjectUtils.isNotEmpty(basketPointSearchVO.getTyProjectCode())) {
            wrapper.eq("ty_project_code", basketPointSearchVO.getTyProjectCode());
        }

        wrapper.orderByDesc("ty_create_time");

        Page<BasketPoint> page = new Page<>();
        page.setPages(basketPointSearchVO.getPage());
        page.setSize(basketPointSearchVO.getRows());

        Page<BasketPoint> basketPointPage = basketPointMapper.selectPage(page, wrapper);
        BasketPointPageVO basketPointPageVO = new BasketPointPageVO();
        basketPointPageVO.setCode(RETURN_CODE);
        basketPointPageVO.setCount(basketPointPage.getTotal());
        basketPointPageVO.setData(basketPointPage.getRecords());

        return ApiResponse.success(basketPointPageVO);
    }

    @Override
    public ApiResponse<BasketPointVO> findOne(String id) {
        BasketPoint basketPoint = basketPointMapper.selectById(id);
        if (ObjectUtils.isNotEmpty(basketPoint)) {
            return ApiResponse.success(BeanUtil.copyProperties(basketPoint, BasketPointVO.class));
        }
        return ApiResponse.fail("该吊篮监测点不存在");
    }

    @Override
    public ApiResponse<List<BasketPointVO>> findByList(BasketPointSearchVO basketPointSearchVO) {
        QueryWrapper<BasketPoint> wrapper = new QueryWrapper<>();

        if(ObjectUtils.isNotEmpty(basketPointSearchVO.getPointName())) {
            wrapper.like("point_name", basketPointSearchVO.getPointName());
        }
        if(ObjectUtils.isNotEmpty(basketPointSearchVO.getTyProjectCode())) {
            wrapper.eq("ty_project_code", basketPointSearchVO.getTyProjectCode());
        }

        wrapper.orderByDesc("ty_create_time");

        List<BasketPoint> basketPoints = basketPointMapper.selectList(wrapper);
        List<BasketPointVO> basketPointVOS = BeanUtil.copyToList(basketPoints,BasketPointVO.class);

        return ApiResponse.success(basketPointVOS);
    }

    @Override
    public ApiResponse<List<DeviceInfoVO>> findDeviceByProductType(BasketPointSearchVO basketPointSearchVO) {
        //todo 没有获取设备信息service
//        List<DeviceInfoVO> list = deviceService.findDeviceByProductType(DeviceTypeEnum.DEVICE_TYPE_BASKET, basketPointSearchVO.getTyProjectCode());
        QueryWrapper<BasketPoint> wrapper = new QueryWrapper<>();
        wrapper.eq("ty_project_code", basketPointSearchVO.getTyProjectCode());
        wrapper.eq("ty_delete_status",0);
        if(StrUtil.isNotEmpty(basketPointSearchVO.getId())) {
            wrapper.ne("id", basketPointSearchVO.getId());
        }
        List<BasketPoint> basketPoints = basketPointMapper.selectList(wrapper);

        Set<String> deviceCodes = new HashSet<>();
        if(basketPoints != null) {
            deviceCodes = basketPoints.stream().map(BasketPoint::getDeviceCode).collect(Collectors.toSet());
        }

        List<DeviceInfoVO> resultList = new ArrayList<>();

        //todo 没有获取设备信息service
//        if(list != null) {
//            for (DeviceInfoVO deviceInfoDto : list) {
//                if(!deviceCodes.contains(deviceInfoDto.getDeviceCode())) {
//                    resultList.add(deviceInfoDto);
//                }
//            }
//        }

        return ApiResponse.success(resultList);
    }

    @Override
    public ApiResponse<String> updateBasketPoint(BasketPointSearchVO basketPointSearchVO) {
        BasketPoint basketPointOld = basketPointMapper.selectById(basketPointSearchVO.getId());
        if (ObjectUtils.isNotEmpty(basketPointOld)) {
            BeanUtils.copyProperties(basketPointSearchVO,basketPointOld);
            basketPointOld.setTyLastUpdateTime(DateUtil.toLocalDateTime(new Date()));
            basketPointOld.setTyLastUpdateUserid("ContextUtil.getUserId()"); //todo
            basketPointOld.setTyLastUpdateUserName("ContextUtil.getUserName()"); //todo

            basketPointMapper.updateById(basketPointOld);
        }
        return ApiResponse.success();
    }

    @Override
    public ApiResponse<String> updateNotice(BasketPointSearchVO basketPointSearchVO) {
        BasketPoint basketPointOld = basketPointMapper.selectById(basketPointSearchVO.getId());
        if (ObjectUtils.isNotEmpty(basketPointOld)) {
            BeanUtils.copyProperties(basketPointSearchVO,basketPointOld);
            basketPointOld.setTyLastUpdateTime(DateUtil.toLocalDateTime(new Date()));
            basketPointOld.setTyLastUpdateUserid("ContextUtil.getUserId()"); //todo
            basketPointOld.setTyLastUpdateUserName("ContextUtil.getUserName()"); //todo

            basketPointMapper.updateById(basketPointOld);
        }
        return ApiResponse.success();
    }

    @Override
    public ApiResponse<String> deleteById(BasketPointSearchVO basketPointSearchVO) {
        BasketPoint basketPoint = basketPointMapper.selectById(basketPointSearchVO.getId());

        if(basketPoint != null){

            basketPoint.setTyDeleteStatus(1);
            basketPoint.setTyLastUpdateTime(DateUtil.toLocalDateTime(new Date()));
            basketPoint.setTyLastUpdateUserid("ContextUtil.getUserId()"); //todo
            basketPoint.setTyLastUpdateUserName("ContextUtil.getUserName()"); //todo

            basketPointMapper.updateById(basketPoint);
        }
        return ApiResponse.success();
    }

    @Override
    public ApiResponse<BasketImgPointVO> findByImgPonitList(BasketPointSearchVO basketPointSearchVO) {
        QueryWrapper<BasketPoint> wrapper = new QueryWrapper<>();

        if(ObjectUtils.isNotEmpty(basketPointSearchVO.getPointName())) {
            wrapper.like("point_name", basketPointSearchVO.getPointName());
        }
        if(ObjectUtils.isNotEmpty(basketPointSearchVO.getTyProjectCode())) {
            wrapper.eq("ty_project_code", basketPointSearchVO.getTyProjectCode());
        }

        wrapper.orderByDesc("ty_create_time");

        List<BasketPoint> basketPoints = basketPointMapper.selectList(wrapper);

//        Map<String, DeviceInfoVO> map = deviceService.findDeviceAndLocationByProductType(DeviceTypeEnum.DEVICE_TYPE_BASKET, basketPointSearchVO.getTyProjectCode());

        String points = "";

//        if(CollectionUtil.isNotEmpty(basketPoints)) {
//            for(BasketPoint point : basketPoints) {
//                if(map.containsKey(point.getDeviceCode())) {
//                    DeviceInfoVO device = map.get(point.getDeviceCode());
//                    point.setDeviceCoordinateX(device.getDeviceCoordinateX());
//                    point.setDeviceCoordinateY(device.getDeviceCoordinateY());
//                    if (StringUtils.isNotEmpty(point.getDeviceCoordinateX()) && StringUtils.isNotEmpty(point.getDeviceCoordinateY())) {
//                        if (StringUtils.isNotEmpty(points)) {
//                            points = points + "," + point.getId();
//                        } else {
//                            points = point.getId();
//                        }
//                    }
//                }
//            }
//        }

        BasketImgPointVO basketImgPointVO = new BasketImgPointVO();
        basketImgPointVO.setPointIds(points);

        List<BasketPointVO> dtos = BeanUtil.copyToList(basketPoints,BasketPointVO.class);
        basketImgPointVO.setSmokeDetectionPointDtos(dtos);

        return ApiResponse.success(basketImgPointVO);
    }

    @Override
    public ApiResponse<List<Map<String, Object>>> findPointCount(BasketPointSearchVO basketPointSearchVO) {
        QueryWrapper<BasketPoint> wrapper = new QueryWrapper<>();

        List<Map<String,Object>> list = new ArrayList<>();

        if(ObjectUtils.isNotEmpty(basketPointSearchVO.getTyProjectCode())) {
            wrapper.eq("ty_project_code", basketPointSearchVO.getTyProjectCode());
        }
        if (StringUtils.isNotEmpty(basketPointSearchVO.getPointIds())) {
            List<String> stringList = Arrays.asList(basketPointSearchVO.getPointIds().split(","));
            wrapper.in("id",stringList);
        }
        Long all = basketPointMapper.selectCount(wrapper);
        Map<String,Object> allMap = new HashMap<>();
        allMap.put("name","监测点位数");
        allMap.put("count",all);
        list.add(allMap);

        QueryWrapper<BasketPoint> wrapper0 = new QueryWrapper<>();
        if(ObjectUtils.isNotEmpty(basketPointSearchVO.getTyProjectCode())) {
            wrapper0.eq("ty_project_code", basketPointSearchVO.getTyProjectCode());
        }
        if (StringUtils.isNotEmpty(basketPointSearchVO.getPointIds())) {
            List<String> stringList = Arrays.asList(basketPointSearchVO.getPointIds().split(","));
            wrapper0.in("id",stringList);
        }
        wrapper0.eq("data_status", 0);
        Long normal = basketPointMapper.selectCount(wrapper0);
        Map<String,Object> normalMap = new HashMap<>();
        normalMap.put("name","安全点位数");
        normalMap.put("count",normal);
        list.add(normalMap);

        QueryWrapper<BasketPoint> wrapper1 = new QueryWrapper<>();
        if(ObjectUtils.isNotEmpty(basketPointSearchVO.getTyProjectCode())) {
            wrapper1.eq("ty_project_code", basketPointSearchVO.getTyProjectCode());
        }
        if (StringUtils.isNotEmpty(basketPointSearchVO.getPointIds())) {
            List<String> stringList = Arrays.asList(basketPointSearchVO.getPointIds().split(","));
            wrapper1.in("id",stringList);
        }
        wrapper1.eq("data_status", 1);
        Long forewarn = basketPointMapper.selectCount(wrapper1);
        Map<String,Object> forewarnMap = new HashMap<>();
        forewarnMap.put("name","预警点位数");
        forewarnMap.put("count",forewarn);
        list.add(forewarnMap);

        QueryWrapper<BasketPoint> wrapper2 = new QueryWrapper<>();
        if(ObjectUtils.isNotEmpty(basketPointSearchVO.getTyProjectCode())) {
            wrapper2.eq("ty_project_code", basketPointSearchVO.getTyProjectCode());
        }
        if (StringUtils.isNotEmpty(basketPointSearchVO.getPointIds())) {
            List<String> stringList = Arrays.asList(basketPointSearchVO.getPointIds().split(","));
            wrapper2.in("id",stringList);
        }
        wrapper2.eq("data_status", 2);
        Long alarm = basketPointMapper.selectCount(wrapper2);
        Map<String,Object> alarmMap = new HashMap<>();
        alarmMap.put("name","报警点位数");
        alarmMap.put("count",alarm);
        list.add(alarmMap);


        return ApiResponse.success(list);
    }
}
